var importProject = {

	dialog : null,
	progressBar : null,
	itemPage : null,
	currentStep : null,
	totalStep : null,
	percentageWith : null,
	prevBtn : null,
	nextBtn : null,
	complateBtn : null,
	fileName : null,
	timestamp : null,
	templatePages : ['pages/cis/project-important.html', 'pages/cis/project-base-info.html', 'pages/cis/project-developer-select.html', 'pages/cis/project-tool-select.html'],
	isLoaded : true,
	baseInfo : null,
	developerInfo : null,
	selectedTools : {},
	jenkinsConfig : null,

	init : function() {
		var self = this;
		self.currentStep = 1;
		self.totalStep = 4;
		self.percentageWith = 0;
		self.isLoaded = true;
		$.get('pages/cis/create-project-template.html').done(function(template) {
			self.dialog = $(template);
			self.dialog.find('.modal-title').text('导入项目')
			self.dialog.modal().on({
				'hidden.bs.modal' : function() {
					$(this).remove();
					self.itemPage.empty();
					self = null;
				}
			});
			self.progressBar = self.dialog.find('#menuBar .progress-bar');
			self.progressBar.css('width', self.percentageWith).find('.sr-only').text('');
			self.itemPage = self.dialog.find('#itemPage');
			$.get(self.templatePages[self.currentStep - 1]).done(function(template) {
				self.itemPage.html(template);
				self.initFileInfo();
			}).fail(function(err) {
				$('body').message({
					type : 'error',
					content : '模板文件不存在!'
				});
			});
			self.prevBtn = self.dialog.find('#prevBtn').hide().on('click', function() {
				self.prev();
			});
			self.nextBtn = self.dialog.find('#nextBtn').hide().on('click', function() {
				self.next();
			});
			self.complateBtn = self.dialog.find('#complateBtn').hide().on('click', function() {
				self.save($(this));
			});
		}).fail(function(err) {
			$('body').message({
				type : 'error',
				content : '模板文件不存在!'
			});
		});
	},

	next : function() {
		var self = this;
		var $btn = self.nextBtn;
		if ($btn.hasClass('disabled') || !self.isLoaded || !self.validateData()) {
			return;
		}
		$btn.addClass('disabled');
		self.prevBtn.show();
		if (self.currentStep == self.totalStep - 1) {
			$btn.removeClass('disabled').hide();
			self.complateBtn.show();
		} else {
			$btn.show();
		}
		self.percentageWith += 100 / self.totalStep;
		self.progressBar.css('width', self.percentageWith + '%').find('.sr-only').text(self.currentStep + '/' + self.totalStep);
		$.get(self.templatePages[self.currentStep]).done(function(template) {
			self.itemPage.empty().html(template);
			self.currentStep++;
			switch (self.currentStep) {
				case 2:
					self.initBaseInfo();
					break;
				case 3:
					self.initDeveloperInfo();
					break;
				case 4:
					self.initToolInfo();
					break;
			}
			$btn.removeClass('disabled');
		}).fail(function(err) {
			$('body').message({
				type : 'error',
				content : '模板文件不存在!'
			});
		});
	},

	validateData : function() {
		var self = this;
		switch(self.currentStep) {
			case 1:
				return self.validateFileInfo();
			case 2:
				return self.validateBaseInfo();
			case 3:
				return self.validateDeveloperInfo();
		}
		return true;
	},

	validateFileInfo : function() {
		var self = this;
		if (!self.baseInfo) {
			self.itemPage.message({
				type : 'warning',
				content : '请上传要导入的项目文件'
			});
			return false;
		}
		return true;
	},

	validateBaseInfo : function() {
		var self = this;
		var projectName = self.itemPage.find('#projectName');
		var groupId = self.itemPage.find('#groupId');
		var artifactId = self.itemPage.find('#artifactId');
		var version = self.itemPage.find('#version');
		var projectNameVal = projectName.val().replace(/(^\s*)|(\s*$)/g, "");
		var groupIdVal = groupId.val().replace(/(^\s*)|(\s*$)/g, "");
		var artifactIdVal = artifactId.val().replace(/(^\s*)|(\s*$)/g, "");
		var versionVal = version.val().replace(/(^\s*)|(\s*$)/g, "");
		if (!Validation.notNull(self.dialog, projectName, projectNameVal, '请输入项目名称')) {
			return false;
		}
		if (!Validation.checkByRegExp(self.dialog, projectName, '^[0-9a-zA-Z_-]*$', projectNameVal, '项目名称不合法')) {
			return false;
		}
		if (/^[0-9]*$/.test(projectNameVal)) {
			showErrorMessage(self.dialog, projectName, '项目名称不合法!');
			return false;
		}
		if (!Validation.notNull(self.dialog, groupId, groupIdVal, '请输入GroupID')) {
			return false;
		}
		if (!Validation.notNull(self.dialog, artifactId, artifactIdVal, '请输入AritifactID')) {
			return false;
		}
		if (!Validation.notNull(self.dialog, version, versionVal, '请输入Version')) {
			return false;
		}
		var flag = false;
		$.ajax({
			url : 'project/is-exist/' + projectNameVal + '.koala',
			type : 'GET',
			async : false
		}).done(function(result) {
			flag = result;
		}).fail(function(err) {
			flag = false;
		});
		if (flag) {
			self.itemPage.message({
				type : 'warning',
				content : '项目名称已存在!'
			});
			return false;
		}
		if (!self.baseInfo) {
			self.baseInfo = {};
		}
		self.baseInfo = {
			projectName : projectNameVal,
			groupId : groupIdVal,
			artifactId : artifactIdVal,
			version : versionVal,
			importProjectSavePath : self.baseInfo.importProjectSavePath
		}
		return true;
	},

	validateDeveloperInfo : function() {
		var self = this;
		var developerGrid = self.itemPage.find('#developerGrid');
		self.developerInfo = developerGrid.getGrid().getAllItems();
		return true;
	},

	prev : function() {
		var self = this;
		var $btn = self.prevBtn;
		if ($btn.hasClass('disabled') || !self.isLoaded) {
			return;
		}
		$btn.addClass('disabled');
		self.nextBtn.show();
		self.complateBtn.hide();
		if (self.currentStep == 2) {
			$btn.removeClass('disabled').hide();

		}
		self.percentageWith -= 100 / self.totalStep;
		self.progressBar.css('width', self.percentageWith + '%').find('.sr-only').text(self.currentStep + '/' + self.totalStep);
		$.get(self.templatePages[self.currentStep - 2]).done(function(template) {
			self.itemPage.empty().html(template);
			self.currentStep--;
			switch (self.currentStep) {
				case 1:
					self.initFileInfo();
					break;
				case 2:
					self.initBaseInfo();
					break;
				case 3:
					self.initDeveloperInfo();
					break;
			}
			$btn.removeClass('disabled');
		}).fail(function(err) {
			self.itemPage.message({
				type : 'error',
				content : '模板文件不存在!'
			});
		});
	},

	initFileInfo : function() {
		var self = this;
		self.itemPage.find('#drag-and-drop-zone').dmUploader({
			url : 'project/upload.koala',
			dataType : 'text',
			allowedTypes: 'zip',
			onFileTypeError: function(){
				
			},
			onUploadSuccess : function(id, data) {
				self.itemPage.find('.point-title').text('文件上传成功，开始解析...');
				$.get('project/resolve.koala?fileName=' + encodeURI(data)).done(function(result) {
					if (result.msg) {
						self.itemPage.find('.point-title').css('color', '#f00').text(result.msg);
					} else {
						self.itemPage.find('.point-title').text('文件解析完成');
						self.baseInfo = {
							projectName : result.name,
							groupId : result.groupId,
							artifactId : result.artifactId,
							version : result.version,
							importProjectSavePath : result.fileSavePath
						};
						self.nextBtn.removeClass('disabled').removeAttr('disabled').show();
						self.nextBtn.click();
					}
				});
			}
		});
	},

	initBaseInfo : function() {
		var self = this;
		self.itemPage.find('#dbProtocol').closest('.form-group').remove();
		self.itemPage.find('#mvcProtocol').closest('.form-group').remove();
		for (var prop in self.baseInfo) {
			self.itemPage.find('#' + prop).val(self.baseInfo[prop]);
		}
	},

	initDeveloperInfo : function() {
		var self = this;
		self.isLoaded = false;
		var developerGrid = self.itemPage.find('#developerGrid').grid({
			identity : 'id',
			columns : [{
				title : '开发者ID',
				name : 'developerId',
				width : 150
			}, {
				title : '用户名',
				name : 'name',
				width : 150
			}, {
				title : '邮箱',
				name : 'email',
				width : 150
			}, {
				title : '操作',
				name : 'id',
				width : 'auto',
				render : function(item, name, index) {
					return '<i class="fa fa-trash-o" onclick="importProject.deleteDeveloper(' + item[name] + ')"></i>';
				}
			}],
			isShowIndexCol : false,
			isShowPages : false,
			isUserLocalData : true,
			localData : self.developerInfo || []
		}).on({
			'complate' : function() {
				self.isLoaded = true;
			}
		});
		var searchElement = self.itemPage.find('#searchValue').on('focus', function() {
			var menu = self.itemPage.find('.typeahead');
			if (menu.find('li').length > 0) {
				menu.show();
			}
		});
		self.itemPage.find('#searchBtn').on('click', function() {
			var searchValue = searchElement.val().replace(/(^\s*)|(\s*$)/g, "");
			if (searchValue.length == 0) {
				self.itemPage.message({
					type : 'warning',
					content : '请输入要添加的开发者ID!'
				});
				return;
			}
			$.get('developer/findby/developerId/' + searchValue + '.koala').done(function(data) {
				data = JSON.parse(JSON.stringify(data).replace(/</g, '&lt;').replace(/>/g, '&gt;'));
				self.itemPage.find('.typeahead').remove();
				var $ul = $('<ul class="dropdown-menu typeahead"></ul>').appendTo(self.itemPage);
				$ul.on('mouseleave', function(){
					$(this).hide();
				});
				var $li = [];
				for (var i = 0, j = data.length; i < j; i++) {
					$li.push('<li data-index="' + i + '"><a>' + data[i].developerId + '(' + data[i].name + ')</a></li>')
				};
				$ul.html($li.join('')).show().find('li').on('click', function() {
					var developer = data[$(this).data('index')];
					var items = developerGrid.getGrid().itemsMap;
					if (!items[developer.id]) {
						developerGrid.getGrid().insertRows(developer);
					}
					$(this).remove()
					$ul.hide();

				});
			}).fail(function(err) {
				self.itemPage.message({
					type : 'error',
					content : '获取开发者失败!'
				});
			});
		});
	},
	initToolInfo : function() {
		var self = this;
		self.isLoaded = false;
		$.get('toolconfiguration/get-all-usable.koala').done(function(data) {
			self.itemPage.find('#toolGrid').grid({
				identity : 'id',
				columns : [{
					title : '工具名',
					name : 'name',
					width : 250
				}, {
					title : '工具类型',
					name : 'toolType',
					width : 250
				}],
				isShowPages : false,
				isUserLocalData : true,
				localData : data
			}).on({
				'selectedRow' : function(e, data) {
					var item = data.item;
					var grid = $(this);
					if (data.checked) {
						for (var id in self.selectedTools) {
							if (item.id != id && item.toolType == self.selectedTools[id].toolType) {
								grid.message({
									type : 'warning',
									content : '每种工具只能选择一个!'
								});
								grid.find('.grid-table-body').find('[data-role="indexCheckbox"][data-value="' + item.id + '"]').removeClass('checked').closest('tr').removeClass('success');
								return;
							}
						}
						if (item.toolType == 'JENKINS') {
							self.initJenkinsConfig();
						}
						self.selectedTools[item.id] = item;
					} else {
						delete self.selectedTools[item.id];
					}
				},
				'complate' : function() {
					self.isLoaded = true;
					var $this = $(this);
					for (var id in self.selectedTools) {
						$this.find('.grid-table-body').find('[data-role="indexCheckbox"][data-value="' + id + '"]').addClass('checked').closest('tr').addClass('success');
					}
				}
			});
		});
	},

	initJenkinsConfig : function() {
		var self = this;
		$.get('pages/cis/jenkins-config.html').done(function(data) {
			var dialog = $(data);
			var scmType = dialog.find('#scmType');
			var repositoryUrl = dialog.find('#repositoryUrl');
			$.get('toolconfiguration/get-scm-type.koala').done(function(data) {
				var contents = [];
				for (var prop in data) {
					contents.push({
						title : prop,
						value : prop
					});
				}
				scmType.select({
					title : '请选择',
					contents : contents
				});
				if (!$.isEmptyObject(self.jenkinsConfig)) {
					scmType.setValue(self.jenkinsConfig.scmType);
					repositoryUrl.val(self.jenkinsConfig.repositoryUrl);
				}
			});
			dialog.modal({
				keyboard : false,
				backdrop : false
			}).on({
				'hidden.bs.modal' : function() {
					$(this).remove();
				}
			});
			dialog.find('#save').on('click', function() {
				if (!Validation.notNull(dialog, scmType, scmType.getValue(), '请选择工具')) {
					return false;
				}
				if (!Validation.notNull(dialog, repositoryUrl, repositoryUrl.val(), '请输入地址')) {
					return false;
				}
				self.jenkinsConfig = {
					scmType : scmType.getValue(),
					repositoryUrl : repositoryUrl.val()
				}
				dialog.modal('hide');
			});
		})
	},
	deleteDeveloper : function(id) {
		this.itemPage.find('#developerGrid').getGrid().removeRows(id);
	},

	deleteTool : function(id) {
		this.itemPage.find('#toolsGrid').getGrid().removeRows(id);
	},

	save : function($btn) {
		var self = this;
		if ($btn.hasClass('disabled')) {
			return;
		}
		$btn.addClass('disabled');
		self.prevBtn.addClass('disabled');
		if ($.isEmptyObject(self.selectedTools)) {
			self.itemPage.find('#toolsGrid').message({
				type : 'warning',
				content : '请选择工具'
			});
			$btn.removeClass('disabled');
			return;
		}
		var projectDto = {};
		projectDto.projectName = self.baseInfo.name;
		projectDto.importProjectSavePath = self.baseInfo.importProjectSavePath;
		projectDto.userCas = self.itemPage.find('#isUseCas').hasClass('checked');
		projectDto.scmConfig = self.jenkinsConfig;
		var projectForCis = {
			name : self.baseInfo.projectName
		};
		projectDto.projectForCis = projectForCis;
		var projectForCreate = {
			groupId : self.baseInfo.groupId,
			artifactId : self.baseInfo.artifactId,
			version : self.baseInfo.version
		}
		projectDto.projectForCreate = projectForCreate;
		projectDto.projectName = self.baseInfo.projectName;
		var projectDeveloperDtos = [];
		$.each(self.developerInfo, function() {
			projectDeveloperDtos.push({
				developerId : this.id
			});
		});
		projectDto.projectDeveloperDtos = projectDeveloperDtos;
		var projectTools = [];
		for (var id in self.selectedTools) {
			var selectedTool = self.selectedTools[id];
			if (selectedTool.toolType == 'JENKINS') {
				projectDto.scmConfig = self.jenkinsConfig;
			}
			projectTools.push({
				id : selectedTool.id,
				toolType : selectedTool.toolType
			});
		}
		projectDto.toolConfigurationDtos = projectTools;
		self.itemPage.loader();
		$.ajax({
			headers : {
				'Accept' : 'application/json',
				'Content-Type' : 'application/json'
			},
			'type' : 'POST',
			'url' : 'project/import.koala',
			'data' : JSON.stringify(projectDto),
			'dataType' : 'json'
		}).done(function(result) {
			self.itemPage.loader('hide');
			if (result.result) {
				self.itemPage.message({
					type : 'success',
					content : '创建成功'
				});
				self.dialog.find('#prevBtn').addClass('disabled').hide();
				$btn.hide();
				self.progressBar.css('width', '100%').find('.sr-only').text(self.totalStep + '/' + self.totalStep);
				self.showProjectProcessMsg(result.msg);
			} else {
				self.itemPage.message({
					type : 'error',
					content : '创建失败'
				});
				$btn.removeClass('disabled');
				self.prevBtn.removeClass('disabled');
			}
		}).fail(function(result) {
			self.itemPage.message({
				type : 'error',
				content : '创建失败'
			});
			$btn.removeClass('disabled');
			self.prevBtn.removeClass('disabled');
			self.itemPage.loader('hide');
		});
	},

	showProjectProcessMsg : function(id) {
		var self = this;
		var intervalId = setInterval(function() {
			$.ajax({
				type : 'GET',
				url : 'project/process/' + id + '.koala',
				async : false
			}).done(function(data) {
				self.itemPage.html(data.msg);
				self.itemPage.scrollTop(self.itemPage[0].scrollHeight);
				if (!data.result) {
					clearInterval(intervalId);
					setTimeout(function() {
						self.dialog.modal('hide');
						window.location.reload();
					}, 3000);
				}
			}).fail(function(err) {
				self.itemPage.html('获取整合信息失败!');
			});
		}, 1000);
	}
};
